//
//  ChatViewController.m
//  AILove
//
//  Created by Ace Portgas on 2023/12/28.
//

#import "ChatViewController.h"
#import "ChatCell.h"
#import "ChatToolBar.h"
#import "VipPopView.h"
#import "ChatFrame.h"
#import "ChatModel.h"
#import "JieGuoView.h"
#import <SJVideoPlayer/SJVideoPlayer.h>
#import "ChongZhiView.h"
@interface ChatViewController ()<UITableViewDelegate,UITableViewDataSource,ChatToolBarDelegate,ChatCellDelegate>
@property (nonatomic,strong)ChatToolBar * toolBar;
@property (nonatomic,strong)UIImageView * backGroundImageView;
@property (nonatomic,strong) NSMutableArray * receivedStrings;
@property (nonatomic,assign)BOOL startPrint;
@property (nonatomic,strong)NSTimer * timer;
@property (nonatomic , strong)SJVideoPlayer * player;
//@property (nonatomic, strong) AVPlayer *audioPlayer;
@property (nonatomic,weak) ChatCell * currentCell;
@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _receivedStrings = [NSMutableArray array];
    [self SQ_Header];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiden:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark -键盘监听方法
- (void)keyboardWasShown:(NSNotification *)notification{
    // 获取键盘的高度
    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [self.toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(-frame.size.height);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 滚动到最后一行
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.jsonArray.count-1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    });
}
- (void)keyboardWillBeHiden:(NSNotification *)notification{
    [self.toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 滚动到最后一行
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.jsonArray.count-1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    });
}

-(void)SQ_Header{
    NSDictionary * dic = @{
        @"current":@"1",
        @"size":@"10",
        @"roomId":self.roomID
    };
    [HttpTool post:LTJL paramDic:[NSMutableDictionary dictionaryWithDictionary:dic] successBlock:^(BaseModel * _Nonnull httpModel) {
        if (httpModel.code == 0) {
            NSArray * array = httpModel.data[@"records"];
            for (NSInteger i = [array count] - 1; i >= 0; i--) {
                ChatModel * model = [ChatModel new];
                [model mj_setKeyValues:array[i]];
                ChatFrame * frame = [ChatFrame new];
                frame.model = model;
                [self.jsonArray addObject:frame];
            }
            [self scrollTaleViewToBottom];
            if (self.jsonArray.count == 1) {
                ChatCell * cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.jsonArray.count-1 inSection:0]];
                [cell playVoice];
            }
        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
}

-(void)SQ_UIViewForSelfView{
    self.view.backgroundColor = [UIColor whiteColor];
    
    _backGroundImageView = [UIImageView new];
    _backGroundImageView.frame = CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT);
//    _backGroundImageView.image = [UIImage imageNamed:@"矩形 19"];
    [_backGroundImageView sd_setImageWithURL:SQURLImage(self.photoURL)];
    _backGroundImageView.contentMode = UIViewContentModeScaleAspectFill;
    _backGroundImageView.layer.masksToBounds = YES;
    [self.view addSubview:_backGroundImageView];
    [_backGroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[ChatCell class] forCellReuseIdentifier:@"ChatCell"];
    
    _toolBar = [[ChatToolBar alloc]init];
    _toolBar.delegate = self;
    [self.view addSubview:_toolBar];
    [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.height.mas_offset(86 + ZXSafeAreaBottom);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.zx_navBar.mas_bottom);
        make.bottom.mas_equalTo(self.toolBar.mas_top);
    }];
}

-(void)scrollTaleViewToBottom{
    // 滚动到最后一行
    NSIndexPath * historyIndexPath = [NSIndexPath indexPathForRow:self.jsonArray.count-1 inSection:0];
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:historyIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

-(void)startPrintText{
    // 定义一个计数器
    __block NSInteger currentIndex = 0;
    __weak typeof(self) weakSelf = self;
    ChatFrame  * frameModel = self.jsonArray.lastObject;
    NSTimeInterval delay = 0.05; // 每个字符显示的时间间隔
    // 定义一个定时器，每隔0.03秒执行一次
    self.timer = [NSTimer scheduledTimerWithTimeInterval:delay repeats:YES block:^(NSTimer * _Nonnull timer) {
        // 在主队列中执行更新 UI 的操作
        dispatch_async(dispatch_get_main_queue(), ^{
            // 判断是否已经拼接完所有的字符串
            if (currentIndex < weakSelf.receivedStrings.count) {
                @autoreleasepool {
                    // 获取当前需要拼接的字符串
                    NSString *stringToAppend = weakSelf.receivedStrings[currentIndex];
                    // 将字符拼接到模型中
                    ChatModel * model = frameModel.model;
                    model.content = [NSString stringWithFormat:@"%@%@",model.content,stringToAppend];
                    frameModel.model = model;
                    NSLog(@"%@",model.content);
                    // 在这里可以进行模型相关操作，例如更新UI等
                    NSIndexPath * historyIndexPath = [NSIndexPath indexPathForRow:weakSelf.jsonArray.count-1 inSection:0];
//                    [weakSelf.tableView reloadRowsAtIndexPaths:@[historyIndexPath] withRowAnimation:UITableViewRowAnimationNone];
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView scrollToRowAtIndexPath:historyIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                }
                if (currentIndex == 0) {
                    ChatCell * cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.jsonArray.count-1 inSection:0]];
                    [cell playVoice];
                }
                currentIndex++;
            } else {
                weakSelf.startPrint = NO;
                [weakSelf.receivedStrings removeAllObjects];
                [weakSelf.timer invalidate];
                weakSelf.timer = nil;
            }
        });
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

-(void)sendMessageWithText:(NSString *)string{
    [self.view endEditing:YES];
    NSLog(@"输入:%@",string);
    ChatModel * sendModel = [ChatModel new];
    sendModel.content = string;
    sendModel.sendType = 0;
    sendModel.roomId = self.roomID;
    sendModel.createTime = [NSString stringWithFormat:@"%@",[NSDate date]];
    ChatFrame * sendFrame = [ChatFrame new];
    sendFrame.model = sendModel;
    [self.jsonArray addObject:sendFrame];
    [self scrollTaleViewToBottom];
    
    ChatModel * model = [[ChatModel alloc]init];
    model.content = @"";
    model.sendType = 1;
    ChatFrame * frame = [ChatFrame new];
    frame.model = model;
    [self.jsonArray addObject:frame];
    [self scrollTaleViewToBottom];
    NSDictionary * dic = @{
        @"content":string,
        @"roomId":self.roomID
//        @"roomId":@"0"
    };
    WS(weakSelf);
    [HttpTool post:FSXX paramDic:[NSMutableDictionary dictionaryWithDictionary:dic] successBlock:^(BaseModel * _Nonnull httpModel) {
        if (httpModel.code == 0) {
            if (weakSelf.startPrint == NO) {
                ChatFrame  * frameModel = self.jsonArray.lastObject;
                ChatModel * model = [[ChatModel alloc]init];
                [model mj_setKeyValues:httpModel.data];
                model.content = @"";
                frameModel.model = model;
                weakSelf.startPrint = YES;
                [weakSelf.receivedStrings removeAllObjects];
                NSDictionary * dic = httpModel.data;
                NSString * text = dic[@"content"];
                for (NSUInteger i = 0; i < [text length]; i++) {
                    unichar character = [text characterAtIndex:i];
                    NSString *characterString = [NSString stringWithCharacters:&character length:1];
                    [weakSelf.receivedStrings addObject:characterString];
                }
                [weakSelf startPrintText];
            }
            [weakSelf.toolBar clearText];
        }else{
            [YJProgressHUD showMessage:httpModel.message afterDelaytime:2];
        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
         if (httpModel.code == -33) {//弹窗系统评分
            [self SQ_goumaichenggong];
        } else if (httpModel.code == -4) {//充值弹窗
            [self SQ_zuanshi];
        } else if (httpModel.code == -44) {//聊天次数达到上限
            [self SQ_numbercount];
        } else {
            [YJProgressHUD showMessage:httpModel.message afterDelaytime:2];
        }
        // 移除最后两个元素
        [weakSelf.jsonArray removeLastObject];
        [weakSelf.jsonArray removeLastObject];
        [weakSelf scrollTaleViewToBottom];
    }];
}

-(void)getGiveLiwu{
    [HttpTool post:Url23 paramDic:[NSMutableDictionary dictionary] successBlock:^(BaseModel * _Nonnull httpModel) {
        
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
}

-(void)SQ_goumaichenggong{
    JieGuoView * vc = [[JieGuoView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    vc.oneLabel.text = SQNSLocalString(@"5星好评赠送聊天次数");
    vc.towLabel.text = SQNSLocalString(@"5星好评并抒写评论\n赠送随机(1-50) 聊天次数");
    vc.btn.text = SQNSLocalString(@"去好评");
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                           parentView:nil
                                             popStyle:LSTPopStyleFade dismissStyle:LSTDismissStyleFade];
    pop.hemStyle = LSTHemStyleCenter;
    pop.isStack = YES;
    [pop pop];
    LSTPopViewWK(pop)
    WS(weakSelf);
    [vc setJGBlock:^{
        [wk_pop dismiss];
        if ([SKStoreReviewController respondsToSelector:@selector(requestReviewInScene:)]) {
            NSArray *array =[[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene *windowScene = (UIWindowScene *)array[0];
            [SKStoreReviewController requestReviewInScene:windowScene];
        }
        [weakSelf getGiveLiwu];
    }];
}

-(void)SQ_zuanshi{
    ChongZhiView * vc = [[ChongZhiView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                           parentView:nil
                                             popStyle:LSTPopStyleFade dismissStyle:LSTDismissStyleFade];
    pop.hemStyle = LSTHemStyleCenter;
//    pop.isStack = YES;
    [pop pop];
    LSTPopViewWK(pop)
    [vc.guanbi setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [wk_pop dismiss];
    }];
    [vc setCZBlock:^(BOOL isOk) {
        [wk_pop dismiss];
    }];
}
//次数达到上限
-(void)SQ_numbercount{
    JieGuoView * vc = [[JieGuoView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    vc.type = 1;
    vc.oneLabel.text = SQNSLocalString(@"聊天次数达到每日限制");
    vc.towLabel.text = SQNSLocalString(@"你的聊天次数达到每日限制，当日继续聊天每次扣除1钻石。次日零点刷新免费聊天次数哦~");
    vc.btn.text = SQNSLocalString(@"好的");
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                           parentView:nil
                                             popStyle:LSTPopStyleFade dismissStyle:LSTDismissStyleFade];
    pop.hemStyle = LSTHemStyleCenter;
    pop.isStack = YES;
    [pop pop];
    LSTPopViewWK(pop)
    [vc setJGBlock:^{
        [wk_pop dismiss];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.jsonArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatFrame * frame = self.jsonArray[indexPath.row];
    return frame.cellHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell"];
    if (!cell) {
        cell = [[ChatCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ChatCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.frameModel = self.jsonArray[indexPath.row];
    cell.cover = self.photoURL;
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
    // 处理其他点击操作
}

 
-(void)playVoiceWithUrl:(NSString *)url andCell:(nonnull ChatCell *)cell{
    self.currentCell = cell;
    WS(weakSelf);
    self.player.assetURL = [NSURL URLWithString:[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    [self.player.playbackObserver setPlaybackDidFinishExeBlock:^(__kindof SJBaseVideoPlayer * _Nonnull player) {
        [weakSelf.currentCell.voice.imageView stopAnimating];
    }];
  
     
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnable:NO];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];
}

- (SJVideoPlayer *)player{
    if (!_player) {
        _player = [SJVideoPlayer player];
//        _player.defaultEdgeControlLayer.hiddenBackButtonWhenOrientationIsPortrait = YES;
//        _player.automaticallyPerformRotationOrFitOnScreen = YES;
//        _player.defaultEdgeControlLayer.hiddenBottomProgressIndicator = NO;
////        _player.pauseWhenAppDidEnterBackground = NO;
////        _player.defaultEdgeControlLayer.onlyUsedFitOnScreen = NO;
//        _player.defaultEdgeControlLayer.automaticallyShowsPictureInPictureItem = NO;
////        _player.controlLayerAppearManager.interval = 5; // 设置控制层隐藏间隔
//        _player.resumePlaybackWhenAppDidEnterForeground = YES;//进入前台时, 是否恢复播放. 默认为 NO
    }
    return _player;
}

@end
